from flask import Flask,current_app,request,jsonify
from flask_cors import CORS
from config.myconfig import myconfig
from project.group_bp import group_bp
from project.company import bp_company
from project.ac_bpl import bp_acl
import logging
from logging import FileHandler
import datetime
from utils.mytoken import token1
from utils.acl import acl



def create_app():
    app = Flask(__name__)
    app.config.from_object(myconfig)
    app.register_blueprint(group_bp)
    app.register_blueprint(bp_company)
    app.register_blueprint(bp_acl)

    CORS(app)
    with app.app_context():
        pass
    return app
app = create_app()


@app.before_request
def before_request():
    white = ["/login"]
    try:
        token = request.headers.get("Token")
    except:
        token = None
    if token:
        user = token1.decode_jwt(token,"123")
        if user:
            reslist = acl.get_reslist(user["id"])
            for i in reslist:
                white.append(i)
            if request.path not in white:
               return jsonify({"code":403,"msg":"fail"})
            else:
                return jsonify({"code": 40313, "msg": "no authorzation"})
        else:
            return jsonify({"code":40312,"msg":"your token has a question"})
    else:
        if request.path not in white:
            return jsonify({"code":40311,"msg":"no token"})


if __name__ == '__main__':
    filename = datetime.datetime.now().strftime("%Y%m")
    handler = logging.FileHandler('logs/'+filename+".txt")
    app.logger.addHandler(handler)
    app.run(debug=True)